package com.mediacloud.app.newsmodule.fragment.videomonitor.vod;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.mediacloud.app.cloud.ijkplayersdk.video.VideoPlayer;
import com.mediacloud.app.model.utils.ViewUtils;
import com.mediacloud.app.newsmodule.model.VideoPlayObj;
import com.mediacloud.app.newsmodule.model.VideoPlayerListenerImpl;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.XKey;
import com.tencent.mmkv.MMKV;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by yoake on 2018/3/22.
 * update by wy （从天王那儿复制过来的，专门用作普通容器装载视频播放播放器使用）
 */

public class ContainerPlayerUtil {

    private Context context;
   private volatile XPlayer mPlayer;
    private Object mark = System.currentTimeMillis();
//    private RecyclerView listView;
    private RelativeLayout container;
    private View rootView;
    public View mengban;

    public ContainerPlayerUtil(Context context) {
        this.context = context;
//        this.listView = listView;
        initPlayer();
        setVideoPlayerListener();
        setListViewOnScrollListener();
    }

    private void initPlayer() {
        XPlayer tmp = new XPlayer(context);
mPlayer = tmp;
        //mPlayer.hideButtonBack();
        mPlayer.allowHardDecode=false;//用软解码  不然全屏在导航头的时候 会一直黑屏一段时间有问题
        mPlayer.fullScreenAdd2WindowContentLayer=true;
        mPlayer.setNonWifiTipsMainColor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).getMainColor());
        mPlayer.setDamuEnable(false);
        //mPlayer.setvideoQualityTitleViseble(View.GONE);
        //mPlayer.showShareIcon(View.GONE);
        //mPlayer.showSmallTitle(View.GONE);
        mPlayer.toggleFullScreenEnable(false);
        //mPlayer.setFullScreenBtnVisible(View.VISIBLE);
        mPlayer.setSmallView(View.GONE);
        mPlayer.controlBarViewControl.showReplayBtn();
        mPlayer.showPlayCenterButton(false);
        mPlayer.setOnPlayerListener(new VideoPlayerListenerImpl()
        {
            @Override
            public void onPrepared(int currentMediaIndex) {
                super.onPrepared(currentMediaIndex);
                if(mPlayer!=null&&!mPlayer.isShown())
                {
                    pausePlay();
                }
            }
        });
    }


    /**
     * 设置播放器的容器
     *
     * @param container 播放器的容器
     */
    public void setPlayerContainer(RelativeLayout container, View view) {
        if (this.mengban != null && this.mengban != view) this.mengban.setVisibility(View.VISIBLE);
        this.mengban = view;
        if (mPlayer == null)
            return;
        mPlayer.stop(true);
        this.container = container;

//        this.rootView = rootView;
        if (mPlayer.getParent() != null) {
            RelativeLayout rl = (RelativeLayout) mPlayer.getParent();
            rl.removeView(mPlayer);
        }

        this.container.addView(mPlayer, params);
    }
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    /**
     * 释放资源，移除父布局
     */
    public void stopPlay() {
        if (mPlayer != null)
            mPlayer.stop(true);
        if (mPlayer != null && mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
    }

    public void pausePlay() {
        if (mPlayer != null) {
            mPlayer.pause();
        }
    }

    /**
     * 监听ListView 滚动
     */
    private void setListViewOnScrollListener() {

       /* listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (rootView != null && listView != null)
                    if (rootView.getBottom() <= 20 || rootView.getTop() >= listView.getHeight() - 40) {
                        stopPlay();
                    }
            }
        });
        listView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if (View.GONE==visibility){
                    Log.e("wywwy","不可见");
                }else {
                    Log.e("wywwy","可见");
                }
            }
        });*/
    }


    public void setVideoData(JSONObject video) {
        KillMusicUtils.stopAPS(context);
        if (video != null) {

            mPlayer.stop();
            mPlayer.setErrorViewVisible(View.GONE);
            try {

                String poster = video.optString("poster", "");
                mPlayer.setPoster(poster,AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
                JSONArray tsAddress = VideoAddressGet.getAddress(video);

                VideoPlayObj videoPlayObj = new VideoPlayObj();
                String cdnEncypt = video.optString("cdnConfigEncrypt");
                videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                videoPlayObj.setTitle("");
                videoPlayObj.setVID("");
                for (int i = 0; i < tsAddress.length(); i++) {
                    JSONObject line = tsAddress.optJSONObject(i);
                    VideoPlayObj.VideoLineItem lineItem = new VideoPlayObj.VideoLineItem();
                    lineItem.setAddress(line.optString("url"));
                    lineItem.setQuality(line.optString("title"));
                    lineItem.setCdnEncypt(cdnEncypt);
                    videoPlayObj.getMediaItem().add(lineItem);
                }
                mPlayer.getMediaObjs().clear();
                mPlayer.addMediaObjs(videoPlayObj);
                if (videoPlayObj.getMediaItem().size() > 0) {
                    mPlayer.showLoadingView();
                    mPlayer.playVideobj(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
                mPlayer.setErrorViewVisible(View.VISIBLE);
            }
        } else {
            mPlayer.setErrorViewVisible(View.VISIBLE);
        }
    }

    /**
     * 设置播放器各种监听
     */
    private void setVideoPlayerListener() {

        mPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
            @Override
            public void onpause(int currentMediaIndex) {
                super.onpause(currentMediaIndex);

            }

            @Override
            public void oncomplete(int currentMediaIndex) {
                super.oncomplete(currentMediaIndex);
                if (mPlayer.isFullScreen()) {
                    mPlayer.toggleFullScreen();
                }
                mPlayer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stopPlay();
                    }
                }, 800);
            }

            @Override
            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
                if (isFullScreen) {
                    ViewGroup rootView = ViewUtils.searchTintContextHostActivity(context).findViewById(android.R.id.content);
                    ViewGroup parent = (ViewGroup) mPlayer.getParent();
                    FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                    parent.removeView(mPlayer);
                    rootView.addView(mPlayer, frameLayoutParams);
                } else {
                    if (mPlayer != null && mPlayer.getParent() != null) {
                        ViewGroup parent = (ViewGroup) mPlayer.getParent();
                        parent.removeView(mPlayer);
                    }
                    if (mPlayer != null) {
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                        container.addView(mPlayer, params);
                    }
                }
            }

            @Override
            public void onPrepared(int currentMediaIndex) {
                super.onPrepared(currentMediaIndex);
                mPlayer.toggleFullScreenEnable(true);
            }
        });

    }

    public void onDestroy() {
        if (mPlayer != null) {
            mPlayer.stop(true);
            mPlayer.release();
            mPlayer = null;
        }
    }

    public VideoPlayer getPlayer() {
        return mPlayer;
    }

    public void setAutoPlay(){
        mPlayer.setAutoPlay(MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false));
    }
}